#!/bin/bash
# This scripts builds a self-contained executable file for Dr.ASan.
# Usage:
#   ./make-self-contained-drasan.sh path/to/dynamorio/exports resulting_binary

# Take the DynamoRIO installation from here:
IN_DIR="$1"
# Put the result here:
OUT="$2"

set -e
rm -f $OUT && touch $OUT && chmod +x $OUT

# Create the header.
cat << 'EOF' >> $OUT
#!/bin/bash
# This is a self-extracting executable of Dr.ASan.
#
# Use like so:
EOF

echo "# $ ./$(basename $OUT) -- <binary-built-with-asan> <flags>" >> $OUT

cat << 'EOF' >> $OUT

# This file is autogenerated by make-self-contained-drasan.sh
# Gory auto-generated details of self-extracting machinery below.
#####################################################################
#
# We extract the temporary files to $DRASAN_EXTRACT_DIR/drasan.XXXXXX
DRASAN_EXTRACT_DIR=${DRASAN_EXTRACT_DIR:-/tmp}
EXTRACT_DIR="$(mktemp -d $DRASAN_EXTRACT_DIR/drasan.XXXXXX)"

cleanup() {
  rm -rf $EXTRACT_DIR
}
# We will cleanup on exit.
trap cleanup EXIT

# Create the dir.
mkdir -p $EXTRACT_DIR
chmod +rwx $EXTRACT_DIR
EOF
# end of header

# Create the runner
cat << 'EOF' >> $OUT
# Extract the end of the file:
sed '1,/^__HERE_BE_DRAGONS__$/d' $0 | tar xz -C $EXTRACT_DIR

# Run
EOF

echo "\$EXTRACT_DIR/bin64/drrun -disable_traces -c \$EXTRACT_DIR/libdr_asan.so \"\$@\"" >> $OUT

cat << 'EOF' >> $OUT
EXIT_STATUS=$?
cleanup  # NOTE: the trap above will handle the cleanup only if we are in bash 3.x
exit $EXIT_STATUS  # make sure to return the exit code from the tool

__HERE_BE_DRAGONS__
EOF

# Dump the compressed binary at the very end of the file.
(cd $IN_DIR && tar zcvh *) >> $OUT || exit 1

echo "File $OUT successfully created"
